package whisper.service.aspect;

import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import whisper.common.support.DatePattern;
import whisper.common.utils.DateUtils;
import whisper.service.constants.TaskStatus;
import whisper.service.domain.db.Task;
import whisper.service.service.TaskService;

/**
 * Created by JT on 2018/5/7
 */
@Component
@Aspect
public class TaskAsept {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TaskService taskService;

    @Pointcut(value = "execution(* whisper.service.coder.Transcoder.run(..)) && args(task)")
    public void transcodeMedia(Task task) {}

    @Before(value = "transcodeMedia(task)")
    public void beforeTranscodeMedia(Task task) {
        if (task.getTaskStatus() < TaskStatus.RETRY_1.getCode() || task.getTaskStatus() > TaskStatus.RETRY_3.getCode()) {
            task.setTaskStartTime(DateUtils.getNowFormat(DatePattern.DATE_PATTERN_STANDARD));
            task.setTaskStatus(TaskStatus.RUNNING.getCode());
            taskService.updateTaskById(task);
        }
        logger.info("转码任务开始执行，文件开始转码！[文件路径: {}, 开始时间: {}, 状态:{}]", task.getSourcePath(), task.getTaskStartTime(), TaskStatus.getValue(task.getTaskStatus()));
    }

    @AfterReturning(value = "transcodeMedia(task)")
    public void afterTranscodeMediaSuccess(Task task) {
        task.setTaskFinishTime(DateUtils.getNowFormat(DatePattern.DATE_PATTERN_STANDARD));
        task.setTaskStatus(TaskStatus.SUCCESS.getCode());
        taskService.updateTaskById(task);
        logger.info("转码任务执行结束，文件转码成功！[文件路径: {}, 结束时间: {}, 状态:{}]", task.getTargetPath(), task.getTaskFinishTime(), TaskStatus.getValue(task.getTaskStatus()));
    }


    @AfterThrowing(value = "transcodeMedia(task)")
    public void afterTranscodeMediaFailed(Task task) {
        task.setTaskFinishTime(DateUtils.getNowFormat(DatePattern.DATE_PATTERN_STANDARD));
        task.setTaskStatus(task.getTaskStatus() + 1);
        taskService.updateTaskById(task);
        logger.error("转码任务执行中止，文件转码失败！[文件路径: {}, 结束时间: {}, 状态:{}]", task.getTargetPath(), task.getTaskFinishTime(), TaskStatus.getValue(task.getTaskStatus()));
    }
}
